import json

from app.services.doubao.interface import UBALDOInterface
from app.services.doubao.model_registry import register_model


@register_model("else_image")
class ElseBasedUBALDO(UBALDOInterface):
    def recognize(self, file_path: str, full_text: str = "") -> dict:
        from app.services.tenant_config_service import get_tenant_config
        from openai import OpenAI
        from app.config import exConfig
        from app.services.doubao.utils import image_to_base64

        tenant_config = get_tenant_config().get_doubao_ai_config()

        b64 = image_to_base64(file_path)
        client = OpenAI(
            base_url="https://ark.cn-beijing.volces.com/api/v3",
            api_key=tenant_config.get('api_key', exConfig.DOUBAO_API_KEY),
        )
        try:
            response = client.chat.completions.create(
                model=tenant_config.get('model', exConfig.DOUBAO_MODEL_ID),
                messages=[{
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": b64
                            }
                        },
                        {"type": "text",
                         "text":
                             """
                                        "仅输出合法 JSON，不要包含任何注释、换行符、Markdown 代码块、额外文字。"

                                        [
                                           {
                                        "subject": "题目内容",
                                        "solve": "题目解析与答案"
                                        }
                                    ]
                                        """}
                    ]
                }],
                stream=False
            )

            response_text = response.choices[0].message.content
            parsed_result = json.loads(response_text)
            return parsed_result
        except Exception as e:
            print("❌ 图片识别失败：", e)
            return {}


